package desktop.core.playfield.util;

import java.util.ArrayList;
import java.util.List;

import pulpcore.Stage;
import pulpcore.animation.Timeline;
import pulpcore.scene.Scene2D;

public class Replay {
	private final long TIME_START = System.currentTimeMillis();

	/** delayList[0]代表timelineList[0]前的延时 **/
	public List<Long> delayList = new ArrayList<Long>();
	private List<Timeline> timelineList = new ArrayList<Timeline>();

	public void addTimeline(Timeline timeline) {
		delayList.add(System.currentTimeMillis() - TIME_START);
		timelineList.add(timeline);
	}

	public void replay() {
		System.out.println(delayList.size());
		for (int i = 0; i < delayList.size(); i++) {
			long delayTime;
			if (i == 0) {
				delayTime = delayList.get(0);
			} else {
				delayTime = delayList.get(i) - delayList.get(i - 1);
			}
			try {
				Thread.sleep(delayTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			new Thread(new ReplayableTimeline(timelineList.get(i))).start();
		}
	}

	private class ReplayableTimeline implements Runnable {

		private Timeline timeline;

		public ReplayableTimeline(Timeline timeline) {
			this.timeline = timeline;
		}

		@Override
		public void run() {
			if (((Scene2D) Stage.getScene()) != null) {
				((Scene2D) Stage.getScene()).addTimeline(timeline);
			}
		}
	}
}